package com.jetsum.micro.service;

import com.jetsum.api.entity.Order;
import com.jetsum.api.entity.Repo;
import com.jetsum.api.service.OrderService;
import com.jetsum.api.service.RepoService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class OrderHandleServiceImpl implements OrderHandleService {

    private final static Logger log = LoggerFactory.getLogger(OrderHandleServiceImpl.class);

    @Reference
    private OrderService<Order> orderService;
    @Reference
    private RepoService<Repo> repoService;

    //该方法抛出异常才可 异常回滚事务
    @GlobalTransactional(timeoutMills = 30000, name = "cloud-consumer-seata")
    @Override
    public String handle(Integer count) {
        try {

            String xid = RootContext.getXID();
            log.info("xid:" + xid);
            //订单创建
            Order order = new Order();
            order.setOrderNo(System.currentTimeMillis() + "");
            order.setCreatedTime(LocalDateTime.now());
            order.setOrderType(1);
            order.setCreatedBy("test");
            orderService.create(order);

            //库存调整
            Repo repo = new Repo();
            repo.setId(1L);
            repo.setCount(count);
            repoService.adjust(repo);
        } catch (Throwable t) {
            throw t;
        }
        return "success";
    }
}
